#include <iostream>
#include <pthread.h>
#include <unistd.h>

unsigned int g_Count = 0;
unsigned int g_SleepDuration = 5;
void *ThreadFunc(void *p);

int main(int argc, char *argv[]) {
  unsigned int thread_num = 500;

  if (argc > 1) {
    thread_num = atoi(argv[1]);
  }
  if (argc > 2) {
    g_SleepDuration = atoi(argv[2]);
  }

  pthread_t hThread[thread_num];
  for (int i = 0; i < thread_num; i++) {
    int *arg = new int(i);
    pthread_create(&hThread[i], NULL, ThreadFunc, arg);
  }

  for (int i = 0; i < thread_num; i++) {
    pthread_join(hThread[i], NULL);
  }

  std::cout << "Final count: " << g_Count << std::endl;
  return 0;
}

void *ThreadFunc(void *p) {
  int thread_num = *((int *)p);
  delete (int *)p;
  usleep(g_SleepDuration);
  g_Count++;
  usleep(g_SleepDuration);
  return NULL;
}